"use strict";

// Module encapsulating Hangout services.
var hangoutModule = angular.module('HangoutModule', []);

// Service that registers a callback on an angular controller scope for Hangout state changes.
hangoutModule.factory('hangoutStateUpdateRegistration', function() {
	var hangoutApiInstance = function(hangoutStateHandler) {
		gapi.hangout.data.onStateChanged.add(function(stateChangeEvent) {
			try {
				var delta_keys = {}
				for (var i = 0; i < stateChangeEvent.addedKeys.length; ++i) {
					delta_keys[stateChangeEvent.addedKeys[i].key] = stateChangeEvent.addedKeys[i].value;
				}
				hangoutStateHandler(stateChangeEvent.state, delta_keys);
			} catch (err) {
				console.log(err);
			}
		});
	}
	return hangoutApiInstance; 
});

// Service that writes to Hangout state.
hangoutModule.factory('hangoutStateWriter', function() {
	console.log("instantiating hangoutStateWriter");
	var hangoutStateWriterInstance = function(key, val) {
		if (typeof key != "string") {
			console.log("invalid key type", key);
			return;
		} else if (typeof val != "string") {
			console.log("invalid val type", val);
			return;
		}
		console.log("setting [" + key + "] = " + val);
		gapi.hangout.data.setValue(key, val);
	}
	return hangoutStateWriterInstance;
});

hangoutModule.factory('hangoutView', function() {
	console.log("instantiating hangoutView");
	var hangoutViewInstance = new Object();
	hangoutViewInstance.getMyId = function() { return gapi.hangout.getParticipantId(); };
	hangoutViewInstance.getParticipants = function() { return gapi.hangout.getEnabledParticipants(); };
	hangoutViewInstance.getStateVal = function(key) {
		var state = hangoutViewInstance.getFullState();
		console.log("getting [" + key + "] = " + state[key]);
		if (key in state)
			return state[key];
		else
			return null;
	}
	hangoutViewInstance.getMyStateVal = function(key) {
		return hangoutViewInstance.getStateVal(key + "_" + hangoutViewInstance.getMyId());
	}
	hangoutViewInstance.getFullState = function() {
		return gapi.hangout.data.getState();
	}
	hangoutViewInstance.iCanAddWork = function() {
		var my_work = hangoutViewInstance.getMyStateVal("work_requests");
		return (my_work == null || JSON.parse(my_work) == "");
	}
	hangoutViewInstance.registerApiReadyCallback = function(callback) {
		gapi.hangout.onApiReady.add(callback);
	}
	hangoutViewInstance.getMyStateVar = function(key) {
		return key + "_" + hangoutViewInstance.getMyId();
	}
	return hangoutViewInstance;
});